<template>
    <div class="character-select-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Choose AI Character" left-text="Back" left-arrow @click-left="handleBack">
            <template #right>
                <van-icon name="filter-o" @click="showFilterPopup" />
            </template>
        </van-nav-bar>

        <!-- 搜索栏 -->
        <div class="search-section">
            <van-search v-model="searchQuery" placeholder="Search characters..." @search="handleSearch"
                @clear="handleClearSearch" />
        </div>

        <!-- 筛选标签 -->
        <div class="filter-section" v-if="activeFilters.length > 0">
            <div class="filter-tags">
                <van-tag v-for="filter in activeFilters" :key="filter.key" closeable @close="removeFilter(filter.key)"
                    size="small" type="primary">
                    {{ filter.label }}
                </van-tag>
            </div>
        </div>

        <!-- 角色列表 -->
        <div class="characters-section">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-section">
                <van-loading size="24px" vertical>Loading characters...</van-loading>
            </div>

            <!-- 角色网格 -->
            <div v-else-if="filteredCharacters.length > 0" class="characters-grid">
                <CharacterCard v-for="character in filteredCharacters" :key="character.id" :character="character"
                    :selected="selectedCharacter?.id === character.id" @select="selectCharacter"
                    @favorite="toggleFavorite" />
            </div>

            <!-- 空状态 -->
            <van-empty v-else description="No characters found" image="search">
                <van-button type="primary" @click="clearAllFilters">
                    Clear Filters
                </van-button>
            </van-empty>
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-actions" v-if="selectedCharacter">
            <div class="selected-info">
                <div class="selected-avatar">
                    <van-image :src="selectedCharacter.avatar_url || '/default-character.png'" round width="40"
                        height="40" />
                </div>
                <div class="selected-details">
                    <div class="selected-name">{{ selectedCharacter.name }}</div>
                    <div class="selected-personality">{{ selectedCharacter.personality_type }}</div>
                </div>
            </div>
            <van-button type="primary" size="large" @click="confirmSelection" :loading="confirming">
                Continue with {{ selectedCharacter.name }}
            </van-button>
        </div>

        <!-- 筛选弹窗 -->
        <van-popup v-model:show="showFilter" position="bottom" :style="{ height: '60%' }" round closeable
            close-icon-position="top-right">
            <div class="filter-popup">
                <div class="filter-header">
                    <h3>Filter Characters</h3>
                </div>

                <div class="filter-content">
                    <!-- 难度筛选 -->
                    <div class="filter-group">
                        <h4>Difficulty Level</h4>
                        <van-checkbox-group v-model="filterOptions.difficulty">
                            <van-checkbox name="1">Beginner</van-checkbox>
                            <van-checkbox name="2">Easy</van-checkbox>
                            <van-checkbox name="3">Intermediate</van-checkbox>
                            <van-checkbox name="4">Advanced</van-checkbox>
                            <van-checkbox name="5">Expert</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 性格类型筛选 -->
                    <div class="filter-group">
                        <h4>Personality Type</h4>
                        <van-checkbox-group v-model="filterOptions.personality">
                            <van-checkbox name="friendly">Friendly</van-checkbox>
                            <van-checkbox name="professional">Professional</van-checkbox>
                            <van-checkbox name="casual">Casual</van-checkbox>
                            <van-checkbox name="challenging">Challenging</van-checkbox>
                            <van-checkbox name="supportive">Supportive</van-checkbox>
                        </van-checkbox-group>
                    </div>

                    <!-- 收藏筛选 -->
                    <div class="filter-group">
                        <h4>Other</h4>
                        <van-checkbox v-model="filterOptions.favoritesOnly">
                            Show favorites only
                        </van-checkbox>
                    </div>
                </div>

                <div class="filter-actions">
                    <van-button block @click="clearFilters">Clear All</van-button>
                    <van-button type="primary" block @click="applyFilters">
                        Apply Filters
                    </van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { trainingApi, type AiCharacter } from '@/api'
import CharacterCard from '@/components/CharacterCard.vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(true)
const confirming = ref(false)
const searchQuery = ref('')
const showFilter = ref(false)
const characters = ref<AiCharacter[]>([])
const selectedCharacter = ref<AiCharacter | null>(null)

// 筛选选项
const filterOptions = ref({
    difficulty: [] as string[],
    personality: [] as string[],
    favoritesOnly: false
})

// 计算属性
const activeFilters = computed(() => {
    const filters: Array<{ key: string; label: string }> = []

    if (filterOptions.value.difficulty.length > 0) {
        filters.push({
            key: 'difficulty',
            label: `Difficulty: ${filterOptions.value.difficulty.length} selected`
        })
    }

    if (filterOptions.value.personality.length > 0) {
        filters.push({
            key: 'personality',
            label: `Personality: ${filterOptions.value.personality.length} selected`
        })
    }

    if (filterOptions.value.favoritesOnly) {
        filters.push({
            key: 'favorites',
            label: 'Favorites only'
        })
    }

    return filters
})

const filteredCharacters = computed(() => {
    let filtered = characters.value

    // 搜索筛选
    if (searchQuery.value.trim()) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(character =>
            character.name.toLowerCase().includes(query) ||
            character.personality_type.toLowerCase().includes(query) ||
            character.description.toLowerCase().includes(query) ||
            character.tags?.some(tag => tag.toLowerCase().includes(query))
        )
    }

    // 难度筛选
    if (filterOptions.value.difficulty.length > 0) {
        filtered = filtered.filter(character =>
            filterOptions.value.difficulty.includes(character.difficulty_level.toString())
        )
    }

    // 性格类型筛选
    if (filterOptions.value.personality.length > 0) {
        filtered = filtered.filter(character =>
            filterOptions.value.personality.some(type =>
                character.personality_type.toLowerCase().includes(type.toLowerCase())
            )
        )
    }

    // 收藏筛选
    if (filterOptions.value.favoritesOnly) {
        filtered = filtered.filter(character => character.is_favorited)
    }

    return filtered
})

// 方法
const loadCharacters = async () => {
    try {
        loading.value = true
        const response = await trainingApi.getCharacters()
        characters.value = response.data
    } catch (error) {
        console.error('Failed to load characters:', error)
        showToast('Failed to load characters')
    } finally {
        loading.value = false
    }
}

const selectCharacter = (character: AiCharacter) => {
    selectedCharacter.value = character
}

const toggleFavorite = async (character: AiCharacter) => {
    try {
        if (character.is_favorited) {
            await trainingApi.unfavoriteCharacter(character.id)
            character.is_favorited = false
        } else {
            await trainingApi.favoriteCharacter(character.id)
            character.is_favorited = true
        }
    } catch (error) {
        console.error('Failed to toggle favorite:', error)
        showToast('Failed to update favorite')
    }
}

const confirmSelection = async () => {
    if (!selectedCharacter.value) return

    try {
        confirming.value = true

        // 保存选择的角色ID到路由参数中传递

        // 跳转到场景选择页面，传递角色ID
        router.push({
            name: 'ScenarioSelect',
            query: { characterId: selectedCharacter.value.id }
        })
    } catch (error) {
        console.error('Failed to confirm selection:', error)
        showToast('Failed to proceed')
    } finally {
        confirming.value = false
    }
}

const handleSearch = () => {
    // 搜索逻辑已在computed中处理
}

const handleClearSearch = () => {
    searchQuery.value = ''
}

const showFilterPopup = () => {
    showFilter.value = true
}

const removeFilter = (filterKey: string) => {
    switch (filterKey) {
        case 'difficulty':
            filterOptions.value.difficulty = []
            break
        case 'personality':
            filterOptions.value.personality = []
            break
        case 'favorites':
            filterOptions.value.favoritesOnly = false
            break
    }
}

const clearFilters = () => {
    filterOptions.value = {
        difficulty: [],
        personality: [],
        favoritesOnly: false
    }
}

const clearAllFilters = () => {
    clearFilters()
    searchQuery.value = ''
}

const applyFilters = () => {
    showFilter.value = false
}

const handleBack = () => {
    router.back()
}

// 生命周期
onMounted(() => {
    loadCharacters()

    // 如果有预选的角色ID，设置为选中状态
    const preselectedId = route.query.characterId
    if (preselectedId) {
        const character = characters.value.find(c => c.id === Number(preselectedId))
        if (character) {
            selectedCharacter.value = character
        }
    }
})
</script>

<style lang="scss" scoped>
.character-select-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-bottom: 100px;

    .search-section {
        padding: 16px;
        background: white;
        border-bottom: 1px solid #ebedf0;
    }

    .filter-section {
        padding: 12px 16px;
        background: white;
        border-bottom: 1px solid #ebedf0;

        .filter-tags {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
    }

    .characters-section {
        padding: 16px;

        .loading-section {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }

        .characters-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 16px;

            @media (min-width: 768px) {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    }

    .bottom-actions {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 16px;
        border-top: 1px solid #ebedf0;
        display: flex;
        align-items: center;
        gap: 16px;
        box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);

        .selected-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;

            .selected-details {
                .selected-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                }

                .selected-personality {
                    font-size: 12px;
                    color: #646566;
                }
            }
        }
    }

    .filter-popup {
        padding: 20px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .filter-header {
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                font-weight: 600;
                color: #323233;
                margin: 0;
            }
        }

        .filter-content {
            flex: 1;
            overflow-y: auto;

            .filter-group {
                margin-bottom: 24px;

                h4 {
                    font-size: 16px;
                    font-weight: 500;
                    color: #323233;
                    margin: 0 0 12px 0;
                }

                .van-checkbox {
                    margin-bottom: 8px;
                }
            }
        }

        .filter-actions {
            display: flex;
            gap: 12px;
            padding-top: 16px;
            border-top: 1px solid #ebedf0;
        }
    }
}
</style>